import { login, logout, getInfo, getMenus, oauthToken } from '@/api/login';
import { getToken, setToken, removeToken } from '@/assets/js/auth';
import avatar_default1 from '@/assets/images/gender1.png';
import avatar_default2 from '@/assets/images/gender2.png';
import tab from './tab';
import router from '@/router';
import util from '@/assets/js/public';
import { getUserdata } from '@/api/dictapi'
const user = {
	state: {
		tabnav: tab.tabnav,
		token: getToken(),
		refreshToken: '',
		avatar: '',
		user: {},
		userinfo: {},

		// user: { userName: 'qinfumin' },
		// userinfo: {
		//
		// 	// belongCompanyTypeDictValue: 01省公司，02市公司，03县公司
		// 	belongCompanyTypeDictValue: '02',
		// 	belongCompanyName: '郑州分公司',
		// 	belongDepartmentName: '政企客户部',
		// 	belongOrgName: '信息服务能力中心',
		// 	truename: '郝鑫',
		// 	preferredMobile: '17837101969',
		//
		// 	authPermissions: [
		// 		{ remark: '应标支撑', permissionCode: 'preSale:answer' },
		// 		{ remark: '方案支撑', permissionCode: 'preSale:scheme' },
		// 		{ remark: '售前拜访', permissionCode: 'business:visit' },
		// 		{ remark: '新增商机', permissionCode: 'business:management' },
		//
		// 		{ remark: '项目进度', permissionCode: 'preSale:initProjectProcess' },
		// 		{ remark: '项目开工', permissionCode: 'preSale:initProjectStart' },
		// 		{ remark: '项目变更', permissionCode: 'preSale:projectChange' },
		// 		{ remark: '项目交接', permissionCode: 'preSale:projecthandover' },
		// 		{ remark: '商机转项目', permissionCode: 'preSale:transitionProject' },
		// 		{ remark: 'CA借用', permissionCode: 'preSale:caReturn' },
		// 		{ remark: 'CA归还', permissionCode: 'preSale:caBorrow' },
		// 		{ remark: 'CA归还', permissionCode: 'preSale:caBorrow' },
		// 		{ remark: '合同计划', permissionCode: 'preSale:contractPlan' },
		// 		{ remark: '5G项目管理', permissionCode: 'preSale:fiveGvertical' },
		//		{ remark: '商机研判', permissionCode: 'select:judged' },
		// 	],
		//
		// 	authPositions: [{
		// 		positionName: '一般员工'
		// 	}],
		//
		// },

		roles: [],
		menus: [],
		haszcxjmenu: {},
		hassetmenuadd: {},
		hassetmenu: {},
		haswtsbmenu: {},
		hasjytgmenu: {}
	},


	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token;
			setToken(token);
		},
		SET_REFRESHTOKEN: (state, refreshToken) => {
			state.refreshToken = refreshToken
		},
		SET_USER: (state, user) => {
			state.user = user;
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles;
		},
		SET_MENUS: (state, menus) => {
			state.menus = menus;
		},
		CLOSE_TABALL: state => {
			state.tabnav = [];
		},
		SET_USERINFO: (state, userinfo) => {
			state.userinfo = userinfo;
		},
	},
	actions: {
		//设置token
		SetToken({ commit }) {
			return new Promise((resolve, reject) => {
				let params = {
					client_id: 'c1ebe466-1cdc-4bd3-ab69-77c3561b9dee',
					client_secret: 'd8346ea2-6017-43ed-ad68-19c0f971738b',
					grant_type: 'refresh_token',
					refresh_token: user.state.refreshToken
				}
				console.log(params)
				oauthToken(params).then(response => {
					commit('SET_TOKEN', response.data.accessToken);
					commit('SET_REFRESHTOKEN', response.data.refreshToken);
					resolve(response);
				}).catch(error => {
					reject(error);
				});
			});
		},
		//设置刷新token的参数
		SetRefreshToken({ commit }, data) {
			return new Promise((resolve, reject) => {
				console.log('设置token啊啊', data)
				if (data) {
					console.log(util.aesDecrypt(data.userName));
					commit('SET_REFRESHTOKEN', data.refreshToken);
					commit('SET_TOKEN', data.accessToken);
					commit('SET_USER', { userName: util.aesDecrypt(data.userName) });
					resolve('获取token成功');
				} else {
					reject('获取token失败');
				}
			});
		},
		//登录
		Login({ commit }, userinfo) {
			console.log(userinfo)
			const phone = userinfo.phone?.trim();
			const smscode = userinfo.smscode?.trim();
			return new Promise((resolve, reject) => {
				let params = { phone, grant_type: 'phone', scope: 'all', client_id: 'iservice_maip', client_secret: process.env.VUE_APP_SECRET, appcode: 'maip' };
				if (smscode) {
					params.smscode = smscode;
					params.grant_type = 'phonecode';
				}
				// let params={phone,appcode:'maip'};
				if (phone) {
					login(params).then(response => {
						const data = response;
						const tokenStr = data.access_token;
						commit('SET_TOKEN', tokenStr);
						resolve(response);
					})
						.catch(error => {
							reject(error);
						});
				} else {
					reject({ message: '手机号必传！' });
				}
			});
		},
		//获取用户信息
		GetInfo({ commit }, data) {
			return new Promise((resolve, reject) => {
				console.log(util.aesDecrypt(data.userName));
				getUserdata(Object.assign({
					userName: util.aesDecrypt(data.userName)
				})).
					then(async (result) => {
					if (!result.data) {
						reject({message: '获取用户基础信息失败！'});
						return;
					}
					commit('SET_USERINFO', result.data.data);
					await util.createOperation('跳转', "dict", "")
					resolve('获取用户基础信息完毕！');
				})
			});
			// return new Promise((resolve, reject) => {
			// 	getInfo()
			// 		.then(response => {						
			// 			let data = response.data;
			// 			if (data.authRoles && data.authRoles.length > 0) {
			// 				commit('SET_ROLES', data);
			// 			} else {
			// 				reject('getinfo: roles must be a non-null array !');
			// 			}
			// 			// commit('SET_NAME',data.username);
			// 			//commit('SET_AVATAR',data.icon || avatar_default);
			// 			data.preferredMobileI=data.preferredMobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
			// 			data.photo = data.photo || (data.genderDictValue=='1'?avatar_default1:avatar_default2);
			// 			if ((!process.env.VUE_APP_APPCURRENTUSER) || (process.env.VUE_APP_APPCURRENTUSER && process.env.VUE_APP_APPCURRENTUSER === 'true')) {
			// 				data.currentBloc = data.schoolId || (data.authBlocs.length > 0 ? data.authBlocs[0].id : '');
			// 				data.currentCorp = data.zoneId || (data.authCorps > 0 ? data.authCorps[0].id : '');
			// 			}
			// 			//data.currentCorpName=data.authCorps[0].corpName;

			// 			commit('SET_USER', data);
			// 			resolve(response);
			// 		})
			// 		.catch(error => {
			// 			reject(error);
			// 		});
			// });
		},
		//登出
		LogOut({ commit, state }) {
			return new Promise((resolve, reject) => {
				logout(state.token)
					.then(response => {
						//commit('SET_AVATAR',data.icon);
						commit('SET_USER', {});
						commit('SET_MENUS', []);
						commit('CLOSE_TABALL');
						if (router.options.routes.length > 3)
							router.options.routes.splice(3);
						resolve(response);
					})
					.catch(error => {
						reject(error);
					});
			});
		},
		//前端 登出
		FedLogOut({ commit }) {
			return new Promise(resolve => {
				commit('SET_TOKEN', '');
				commit('SET_MENUS', []);
				commit('CLOSE_TABALL');
				removeToken();
				resolve();
			});
		},
		//获取菜单
		GetMenus({ commit, state }) {
			console.log('GetMenus');
			return new Promise((resolve, reject) => {
				getMenus(state.user.username)
					.then(res => {
						commit('SET_MENUS', res.data);
						commit('CLOSE_TABALL');
						resolve(res);
					})
					.catch(error => {
						reject(error);
					});
			});
		}
	}
};
export default user;
